package com.hefan.api.controller.user;

import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.common.meta.SmsCodeTypeEnum;
import com.cat.common.util.EncryptionUtil;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.api.bean.LoginTokenVo;
import com.hefan.api.bean.LoginUserVo;
import com.hefan.api.service.LoginTokenLocalService;
import com.hefan.api.service.SmsLocalService;
import com.hefan.api.service.UserLocalService;
import com.hefan.api.service.point.PointLocalService;
import com.hefan.common.point.bean.BuriedPointVo;
import com.hefan.common.util.HttpUtils;
import com.hefan.user.bean.LoginToken;
import com.hefan.user.bean.WebUser;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by lxw on 2016/9/26.
 */
@Controller
@RequestMapping("/v1/login")
public class LoginController {

    public static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private UserLocalService userLocalService;
    @Resource
    private LoginTokenLocalService loginTokenLocalService;
    @Resource
    private SmsLocalService smsLocalService;
    @Resource
    private PointLocalService pointLocalService;
    /**
     * 用户登陆
     * @param request
     * @return
     */
    @RequestMapping(value ="/userLogin")
    @ResponseBody
    public String userLogin(HttpServletRequest request) {
        //Profiler profiler = new Profiler("userLogin--start");
        ResultBean resBean = new ResultBean(ResultCode.SUCCESS,null);
        try {
            LoginUserVo loginUserVo = HttpUtils.initParam(request,LoginUserVo.class);
			if (loginUserVo == null || StringUtils.isBlank(loginUserVo.getDeviceNo())
					|| StringUtils.isBlank(loginUserVo.getMobile()) || StringUtils.isBlank(loginUserVo.getMsCode())) {
				return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
			}
            String deviceNo = loginUserVo.getDeviceNo();
            String mobile = loginUserVo.getMobile();
            String passwords = loginUserVo.getMsCode();
            WebUser webUser = null;
            if(mobile.length() != 11){ //内部员工登陆| 虚拟用户|明星用户登陆[mobile 为userId]
                //profiler.start("userLogin--getWebUserByUserId--runTime@@");
                webUser = userLocalService.getWebUserByUserId(mobile);
                if(webUser == null) { //不存在返回错误
                    return JSON.toJSONString(new ResultBean(ResultCode.LoginUserIsNotExist,null));
                }
                if(!EncryptionUtil.getMd5Value(passwords+ GlobalConstants.PASSWORD_SUFFIX).equals(webUser.getPasswords())) { //密码错误
                    return  JSON.toJSONString(new ResultBean(ResultCode.LoginUserPasswordError, null));
                }
            } else { //用户手机号登陆
                //验证短信验证码是否正确
                //profiler.start("userLogin--checkSmsCode--runTime@@");
                ResultBean smsCheckResBean = smsLocalService.checkSmsCode(SmsCodeTypeEnum.LOGIN_SMS_CODE_TYPE.getType(),mobile,passwords);
                if(smsCheckResBean.getCode().intValue() != ResultCode.SUCCESS.get_code()) {
                    return JSON.toJSONString(smsCheckResBean);
                }
                //根据手机号获取用户信息
                //profiler.start("userLogin--getWebUserInfoByThridParty--runTime@@");
                webUser = userLocalService.getWebUserInfoByThridParty(4,mobile);
                if(webUser == null) {
                    //初始化新增用户信息
                    loginUserVo.setThirdType(4);
                    webUser = initWebUserCreater(loginUserVo);
                    //注册新用户,并返回用户基础信息
                    //profiler.start("userLogin--saveRegisterUserInfo--runTime@@");
                    ResultBean<WebUser> registResult = userLocalService.saveRegisterUserInfo(webUser,loginUserVo.getThirdType(),mobile);
                    if(registResult.getCode() == ResultCode.SUCCESS.get_code()) {
                        webUser = registResult.getData();
                        this.setToClubIndex(webUser.getUserId());
                        if(webUser != null) {
                            BuriedPointVo buriedPointVo = HttpUtils.reqBuriedPointHeader(request, BuriedPointVo.class);
                            //记录渠道埋点记录
                            //profiler.start("userLogin--recordChannelPointInfo--runTime@@");
                            pointLocalService.recordChannelPointInfo(webUser.getUserId(), buriedPointVo);
                        }
                    } else {
                        return JSON.toJSONString(registResult);
                    }
                }
            }
            //检查用户信息
            resBean = userLocalService.userLoginPubCheck(webUser);
            if(resBean.getCode().intValue() != ResultCode.SUCCESS.get_code()) {
                return JSON.toJSONString(resBean);
            }
            //redis中保存用户登陆token信息
            //profiler.start("userLogin--loginTokenVoCreater--runTime@@");
            String token = loginTokenVoCreater(webUser.getUserId(), loginUserVo.getDeviceNo());
            webUser.setToken(token);
            webUser.setServerTime(System.currentTimeMillis());
            webUser.setToClubStatus(this.getToClubIndex(webUser.getUserId()));
            resBean.setData(webUser);
            if( StringUtils.isNotBlank(loginUserVo.getDeviceToken())) {
                //注册push token
                try {
                    LoginToken tokenParam = new LoginToken();
                    tokenParam.setDeviceToken(loginUserVo.getDeviceToken());
                    tokenParam.setUserId(webUser.getUserId());
                    //profiler.start("userLogin--saveLoginToken--runTime@@");
                    loginTokenLocalService.saveLoginToken(tokenParam);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error(e.getMessage());
                    return JSON.toJSONString(resBean);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return JSON.toJSONString(new ResultBean(ResultCode.UNSUCCESS,null));
        } finally {
            //profiler.stop().print();
        }
        return JSON.toJSONString(resBean);
    }

    /**
     * 第三方登录
     * @return
     */
    @RequestMapping("/thirdLogin")
    @ResponseBody
    public String thirdLogin(HttpServletRequest request) {
        //Profiler profiler = new Profiler("thirdLogin--start");
        ResultBean resBean = new ResultBean(ResultCode.SUCCESS,null);
        try {
            LoginUserVo loginUserVo = HttpUtils.initParam(request, LoginUserVo.class);
			if (loginUserVo == null || StringUtils.isBlank(loginUserVo.getDeviceNo())
					|| StringUtils.isBlank(loginUserVo.getOpenid())) {
				return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
			}
            if("null".equals(loginUserVo.getOpenid())) { //第三方openid非法
                return JSON.toJSONString(new ResultBean(ResultCode.ThridUserOpenIdError, null));
            }
            //profiler.start("thirdLogin--getWebUserInfoByThridParty--runTime@@");
            WebUser webUser = null;
            if(loginUserVo.getThirdType() == 2 && StringUtils.isNotBlank(loginUserVo.getUnionidWx())) {
                //微信登录&&微信unionid不为空 时现根据unionid检查用户是否存在
                webUser = userLocalService.getWebUserInfoByThridParty(5, loginUserVo.getUnionidWx());
            }
            if(webUser == null) {
                webUser = userLocalService.getWebUserInfoByThridParty(loginUserVo.getThirdType(), loginUserVo.getOpenid());
            }
            if(loginUserVo.getThirdType() ==  2) { //如果是微信登录检查wxuid是否存在
                BuriedPointVo buriedPointVo = HttpUtils.reqBuriedPointHeader(request, BuriedPointVo.class);
                resBean = userLocalService.handleWebUserByWxUid(webUser, loginUserVo, buriedPointVo);
                if(resBean.getCode() == ResultCode.SUCCESS.get_code()) {
                    webUser = (WebUser)resBean.getData();
                } else {
                    return JSON.toJSONString(resBean);
                }
            }
            if (webUser == null) { //不存在,进行自动注册操作
                //初始化新增用户信息
                webUser = initWebUserCreater(loginUserVo);
                //注册新用户,并返回用户基础信息
                //profiler.start("thirdLogin--saveRegisterUserInfo--runTime@@");
                ResultBean<WebUser> registResult = userLocalService.saveRegisterUserInfo(webUser,loginUserVo.getThirdType(),loginUserVo.getOpenid());
                if(registResult.getCode() == ResultCode.SUCCESS.get_code()) {
                    webUser = registResult.getData();
                    setToClubIndex(webUser.getUserId());
                    if(webUser != null) {
                        BuriedPointVo buriedPointVo = HttpUtils.reqBuriedPointHeader(request, BuriedPointVo.class);
                        //记录渠道埋点记录
                        //profiler.start("thirdLogin--recordChannelPointInfo--runTime@@");
                        pointLocalService.recordChannelPointInfo(webUser.getUserId(), buriedPointVo);
                    }
                } else {
                    return JSON.toJSONString(registResult);
                }
            }

            if(webUser != null && loginUserVo.getThirdType() ==  2) {
                if(StringUtils.isBlank(webUser.getUnionidWx()) && StringUtils.isNotBlank(loginUserVo.getUnionidWx())) {
                    userLocalService.updateWebUserUnionidWx(webUser.getUserId(),loginUserVo.getUnionidWx());
                }
            }

            //检查用户信息
            resBean = userLocalService.userLoginPubCheck(webUser);
            if (resBean.getCode().intValue() != ResultCode.SUCCESS.get_code()) {
                return JSON.toJSONString(resBean);
            }
            //redis中保存用户登陆token信息
            //profiler.start("thirdLogin--loginTokenVoCreater--runTime@@");
            String token = loginTokenVoCreater(webUser.getUserId(), loginUserVo.getDeviceNo());
            webUser.setToken(token);
            webUser.setServerTime(System.currentTimeMillis());
            webUser.setToClubStatus(this.getToClubIndex(webUser.getUserId()));
            resBean.setData(webUser);
            if( StringUtils.isNotBlank(loginUserVo.getDeviceToken())) {
                //注册push token
                try {
                    LoginToken tokenParam = new LoginToken();
                    tokenParam.setDeviceToken(loginUserVo.getDeviceToken());
                    tokenParam.setUserId(webUser.getUserId());
                    //profiler.start("thirdLogin--saveLoginToken--runTime@@");
                    loginTokenLocalService.saveLoginToken(tokenParam);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error(e.getMessage());
                    return JSON.toJSONString(resBean);
                }
            }
        }catch (Exception e) {
            logger.error(e.getMessage());
            return JSON.toJSONString(new ResultBean(ResultCode.UNSUCCESS,null));
        } finally {
            //profiler.stop().print();
        }
        return JSON.toJSONString(resBean);
    }

    @RequestMapping("/autoLogin")
    @ResponseBody
    public String autoLogin(HttpServletRequest request) {
        //Profiler profiler = new Profiler("autoLogin--start");
        ResultBean resBean = new ResultBean(ResultCode.SUCCESS,null);
        try {
            Map paramMap = HttpUtils.initParam(request,HashMap.class);
            if(paramMap == null || paramMap.isEmpty() || !paramMap.containsKey("token")
                    || StringUtils.isBlank(String.valueOf(paramMap.get("token")))) {
                return JSON.toJSONString(new ResultBean(ResultCode.ParamException,null));
            }
            String token = String.valueOf(paramMap.get("token"));
            //profiler.start("autoLogin--getTokenFromRedis--runTime@@");
            LoginTokenVo tokenInfo = loginTokenLocalService.getTokenFromRedis(token);
            if(tokenInfo == null || StringUtils.isBlank(tokenInfo.getUserId())) {
                return JSON.toJSONString(new ResultBean(ResultCode.LoginAutoOutTime,null));
            }
            //profiler.start("autoLogin--getWebUserByUserId--runTime@@");
            WebUser webUser = userLocalService.getWebUserByUserId(tokenInfo.getUserId());
            if(webUser == null) {
                return JSON.toJSONString(new ResultBean(ResultCode.LoginUserIsNotExist,null));
            }
            //检查用户信息
            resBean = userLocalService.userLoginPubCheck(webUser);
            if(resBean.getCode().intValue() != ResultCode.SUCCESS.get_code()) {
                return JSON.toJSONString(resBean);
            }
            webUser.setToken(token);
            webUser.setServerTime(System.currentTimeMillis());
            webUser.setToClubStatus(getToClubIndex(webUser.getUserId()));
            resBean.setData(webUser);
        }catch (Exception e) {
            logger.error(e.getMessage());
            return JSON.toJSONString(new ResultBean(ResultCode.UNSUCCESS,null));
        } finally {
            //profiler.stop().print();
        }
        return JSON.toJSONString(resBean);
    }

    /**
     * 组装新增用户信息
     * @param loginUserVo
     * @return
     */
    private WebUser initWebUserCreater(LoginUserVo loginUserVo) {
        WebUser webUser = new WebUser();
        switch (loginUserVo.getThirdType()) {
            case 1:
                webUser.setOpenidWb(loginUserVo.getOpenid());
                break;
            case 2:
                webUser.setOpenidWx(loginUserVo.getOpenid());
                webUser.setUnionidWx(loginUserVo.getUnionidWx());
                break;
            case 3:
                webUser.setOpenidQq(loginUserVo.getOpenid());
                break;
            case 4:
                webUser.setMobile(loginUserVo.getMobile());
                break;
            default:
                return null;
        }
        if(!StringUtils.isBlank(loginUserVo.getNickName())) webUser.setNickName(loginUserVo.getNickName());
        if(!StringUtils.isBlank(loginUserVo.getHeadImg())) webUser.setHeadImg(loginUserVo.getHeadImg());
        if(!StringUtils.isBlank(loginUserVo.getQq())) webUser.setQq(loginUserVo.getQq());
        webUser.setUserType(0);
        return webUser;
    }

    /**
     * 组装LoginTokenVo对象
     * @param userId
     * @param deviceNo
     * @return
     */
    private String loginTokenVoCreater(String userId,String deviceNo) throws Exception{
        LoginTokenVo loginTokenVo = new LoginTokenVo("", userId, deviceNo);
        return loginTokenLocalService.loginTokenCreater(loginTokenVo);
    }

    /**
     * 获取用户是否是第一次进入俱乐部 0 是 1不是
     * @param userId
     * @return
     */
    private Integer getToClubIndex(String userId){
        return userLocalService.getToClubIndex(userId);
    }

    /**
     * 设置用户第一次进入俱乐部推进状态
     * @param userId
     */
    private void setToClubIndex(String userId){
        userLocalService.setToClubIndex(userId);
    }
}
